/**
* 业务员-广告-设备管理
*/
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>模拟播放</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="user-search">
      <el-form-item label="搜索：">
        <el-select size="small" v-model="formInline.key" filterable  placeholder="请选择">
          <el-option label="全部" value=""></el-option>
          <el-option
            v-for="item in parking"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <video-player
      class="video-player vjs-custom-skin"
      ref="videoPlayer"
      name="videoPlayer"
      id="video"
      :playsinline="true"
      :options="playerOptions"
      @play="onPlayerPlay($event)"
      @pause="onPlayerPause($event)"
      @ended="onPlayerEnded($event)"
      @waiting="onPlayerWaiting($event)"
      @timeupdate="onPlayerTimeupdate($event)"
      @statechanged="playerStateChanged($event)"
      @canplaythrough="onPlayerCanplaythrough($event)"
      @ready = "playerReadied"
    ></video-player>
  </div>
</template>

<script>
import 'video.js/dist/video-js.css'
import 'videojs-contrib-hls'
import { videoPlayer } from 'vue-video-player'
export default {
  data() {
    return {
// 请求数据参数
      parking:[],
      videoUrl:"",
      params:{
        id:"1",
        adId:"",
        name:"某某停车场的设备"
      },
      requestData:{
        toId:"",
        adId:"",
        apStart:"",
        apEnd:""
      },
      formInline: {
        page: 1,
        limit: 10,
        key: ''
      },
      path: "ws://localhost:80/video/1",
      socket: '',
      playerOptions: {

        //视频播放
        playbackRates: [0.5, 1.0, 1.5, 2.0], // 可选的播放速度
        autoplay: true, // 如果为true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 是否视频一结束就重新开始。
        preload: "auto", // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: "zh-CN",
        aspectRatio: "16:9", // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [
          {
            type: "video/mp4", // 类型
            src:this.videoUrl
          }
        ],
        poster: "", // 封面地址
        notSupportedMessage: "此视频暂无法播放，请稍后再试", // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true, // 当前时间和持续时间的分隔符
          durationDisplay: true, // 显示持续时间
          remainingTimeDisplay: false, // 是否显示剩余时间功能
          fullscreenToggle: true // 是否显示全屏按钮
        },
      }
    }

  },
  // 注册组件
  components: {
    videoPlayer
  },
  computed: {
    player() {
      return this.$refs.videoPlayer.player
    }
  },

  /**
   * 数据发生改变
   */
  watch: {},

  /**
   * 创建完毕
   */
  created() {

  },

  mounted() { // 渲染后执行
    // 初始化
    this.initWebsocket();
  },
  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    //==============webSocket======================
    initWebsocket: function () {
      if(typeof(WebSocket) === "undefined"){
        alert("您的浏览器不支持socket")
      }else{
        // 实例化socket
        this.socket = new WebSocket(this.path)
        // 监听socket连接
        this.socket.onopen = this.open
        // 监听socket错误信息
        this.socket.onerror = this.error
        // 监听socket消息
        this.socket.onmessage = this.getMessage
      }
    },
    open: function () {
      console.log("socket连接成功")
    },
    error: function () {
      console.log("连接错误")
    },

    getMessage: function (msg) {
      console.log("msg"+JSON.stringify(msg))

      let dataJson = JSON.parse(msg.data)

      this.params.adId =dataJson.adId
      this.playerOptions['sources'][0]['src'] = dataJson.url
      //.$refs.videoPlayer.player.play()
      console.log("Websocket返回的地址"+msg.data)
    },

    send: function () {
      this.socket.send(JSON.stringify(this.requestData))
    },
    close: function () {
      console.log("socket已经关闭")
    },
    //==============webSocket======================


    //播放
    // 播放回调
    onPlayerPlay(player) {
      console.log("player 开始!", player);
      this.requestData.apStart = this.getCurrentTime()
      this.requestData.toId = this.params.id
      this.requestData.adId =this.params.adId;

      console.log(this.requestData)
    },

    // 暂停回调
    onPlayerPause(player) {
      console.log("player 暂停!", player);
    },

    // 视频播完回调
    onPlayerEnded($event) {
      console.log("结束");
      this.requestData.apEnd = this.getCurrentTime()
      this.send()
    },
    // DOM元素上的readyState更改导致播放停止
    onPlayerWaiting(player) {
      let time = localStorage.getItem("cacheTime")
      if(player.cache_.currentTime - Number(time) > 0.1){
        this.current = Number(time)
        this.playerReadied(player)
      }else{
        this.current = player.cache_.currentTime
      }
    },
    //获取时间
    getCurrentTime() {
      //获取当前时间并打印
      var _this = this;
      let yy = new Date().getFullYear();
      let mm = new Date().getMonth()+1;
      let dd = new Date().getDate();
      let hh = new Date().getHours();
      let mf = new Date().getMinutes()<10 ? '0'+new Date().getMinutes() : new Date().getMinutes();
      let ss = new Date().getSeconds()<10 ? '0'+new Date().getSeconds() : new Date().getSeconds();
      _this.gettime = yy+'/'+mm+'/'+dd+' '+hh+':'+mf+':'+ss;
      console.log(_this.gettime)
      return _this.gettime
    },
    // 已开始播放回调
    onPlayerPlaying($event) {
      // console.log(player)
    },

    // 当播放器在当前播放位置下载数据时触发
    onPlayerLoadeddata($event) {
      // console.log(player)
    },

    // // 当前播放位置发生变化时触发。
    onPlayerTimeupdate(player) {
      this.playTime = player.cache_.currentTime
      let playTime = player.cache_.currentTime
      setTimeout(function () {
        localStorage.setItem("cacheTime",playTime)
      },500)


      let time = localStorage.getItem("cacheTime")
      if(player.cache_.currentTime - Number(time) > 2){
        this.current = Number(time)
        this.playerReadied(player)
      }else{
        this.current = player.cache_.currentTime
      }
    },

    //媒体的readyState为HAVE_FUTURE_DATA或更高
    onPlayerCanplay(player) {
      // console.log('player Canplay!', player)
    },

    //媒体的readyState为HAVE_ENOUGH_DATA或更高。这意味着可以在不缓冲的情况下播放整个媒体文件。
    onPlayerCanplaythrough(player) {
      // console.log('player Canplaythrough!', player)
    },

    //播放状态改变回调
    playerStateChanged(playerCurrentState) {
      // console.log('player current update state', playerCurrentState)
    },

    //将侦听器绑定到组件的就绪状态。与事件监听器的不同之处在于，如果ready事件已经发生，它将立即触发该函数。。
    playerReadied(player) {
      // console.log('example player 1 readied', player);
      player.currentTime(this.current)
    }
  }
}
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
</style>

